package com.cloud.point.designPattern.strategy;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * DiscountContext
 *
 * @author 24373
 * @version 1.0
 * @date 2024-06-02 16:27
 */
@Component
public class DiscountContext implements ApplicationContextAware {

    private Map<DiscountType, IDiscount> map = new ConcurrentHashMap<>();

    public BigDecimal payService(DiscountType type, BigDecimal price) {
        IDiscount discount = map.get(type);
        if (discount != null) {
            return discount.payService(price);
        }
        return new BigDecimal("-1");
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        Map<String, IDiscount> type = context.getBeansOfType(IDiscount.class);
        type.values().forEach(t -> map.put(t.getType(), t));
    }
}
